package br.com.mundoj.subscription;

import javax.servlet.ServletContextEvent;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;

import com.wideplay.warp.persist.PersistenceService;
import com.wideplay.warp.persist.UnitOfWork;
import com.wideplay.warp.persist.jpa.JpaUnit;

public class GuiceConfigurer extends GuiceServletContextListener {
    private Injector injector;

    @Override
	protected Injector getInjector() {
        injector = Guice.createInjector(
        	PersistenceService.usingJpa().across(UnitOfWork.TRANSACTION).buildModule(),
            new AbstractModule() {
                protected void configure() {
                    //tell Warp the name of the jpa persistence unit
                    bindConstant().annotatedWith(JpaUnit.class).to("default");
                }
            }
        );
		return injector;
	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		super.contextInitialized(servletContextEvent);
        injector.getInstance(PersistenceService.class).start();
	}

	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		super.contextDestroyed(servletContextEvent);
		injector.getInstance(PersistenceService.class).shutdown();
	}
}